<!DOCTYPE html>
<html class="no-js css-menubar" lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
  <meta name="description" content="bootstrap admin template">
  <meta name="author" content="">
  <script type="text/javascript" src="../_resource/js/header.js"></script>
  <script>
    var RUN_FUNCS = [];
	var SITE_URL  = "http://admin.html.me";
	var CURR_CONTROLLER  = "Article";
	var CURR_ACTION  = "add";
    Breakpoints();
  </script>
  <style type="text/css">
    .list-table table td, .list-table table th{background:#fff; text-align:center;}
    .__access{display: none;}
  </style>
  </head>
<body class="dashboard">
  <!--[if lt IE 8]>
  <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
  <![endif]-->

  <nav class="site-navbar navbar navbar-default navbar-fixed-top navbar-mega" role="navigation" id="navbardefaultmodel">
       <script type="text/javascript" src="../_resource/js/include.js" onload="HM.SomeFun('head_html')"></script> 
  </nav>
  <div class="site-menubar">
    <div class="site-menubar-body" id="site-menubar-body">
         <script type="text/javascript" src="../_resource/js/include.js" onload="HM.SomeFun('nav_html')"></script>
    </div>
  </div>

  <!-- Page -->
  <div class="page">
    <div class="page-content container-fluid">
          
<div class="panel form-box" style="">
    <div class="panel-body">
        <form class="validate-form ajax-form" id="bossjobForm" target="_self" autocomplete="off">
            <div id="title-form-item" class="form-group " style="">
                <label for="title" class="control-label ">Title<span class="required">*</span>:</label>
                <div>
                    <input type="text" name="title" id="news-title" class="form-control " style="" placeholder="Article title..."  value="" />
                    <input id="news-id" type="text" value="" style="display: none;">
                </div>
            </div>

            <div id="author-form-item" class="form-group" style="">
                <label for="author" class="control-label ">Author<span class="required">*</span>:</label>
                <div>
                    <input type="text" name="author" id="news-author" class="form-control " style="" placeholder="Article author..."  value="" />
                </div>
            </div>

            <div id="content-form-item" class="form-group" style="">
                <label for="content" class="control-label ">Content<span class="required">*</span>:</label>
                <div>
                    <textarea id="summernote" data-plugin="summernote" name="content" placeholder="Article content..."></textarea>
                </div>
            </div>

            <div class="row" style="padding: 0px 0px 10px 20px;">
                <div id="banner-form-item" class="form-group" style="">
                    <label for="banner" class="control-label">Banner:<span style="color:red;">(width=1600px & height=900px)</span></label>
                    <div>
                        <div class="dropify-photos" style="width:20%;float:left;margin:0px 10px;">
                            <input type="file" name="banner[]" id="input-file-now-custom-1" data-min-width="1599" data-min-height="899" data-max-width="1601" data-max-height="901" class="news-banner-img" data-default-file=""/>
                        </div>
                        <div class="dropify-photos" style="width:20%;float:left;margin:0px 10px;">
                            <input type="file" name="banner[]" id="input-file-now-custom-2" data-min-width="1599" data-min-height="899" data-max-width="1601" data-max-height="901" class="news-banner-img" data-default-file=""/>
                        </div>
                        <div class="dropify-photos" style="width:20%;float:left;margin:0px 10px;">
                            <input type="file" name="banner[]" id="input-file-now-custom-3" data-min-width="1599" data-min-height="899" data-max-width="1601" data-max-height="901" class="news-banner-img" data-default-file=""/>
                        </div>
                    </div>
                </div>
            </div>

            <div id="category_id-form-item"  class="form-group " style="" >
                <label for="category_id" class="control-label ">Category:</label>
                <div>
                    <select class="form-control form-control-sm" name="category_id" id="news-category-select">
                        <option value="0">Please select</option>
                    </select>
                </div>
            </div>

            <div id="status-form-item" class="form-group" style="">
                <label for="status" class="control-label">Status:</label>
                <div>
                    <select class="form-control form-control-sm" name="status" id="news-status" disabled="disabled">
                        <option value="0">Unknown</option>
                        <option value="1">Draft</option>
                        <option value="2">Published</option>
                        <!-- <option value="2" >Scheduled to publish</option> -->
                    </select>
                </div>
            </div>

            <button type="button" class="btn btn-success" id="save-news-btn" data-status="2" disabled="disabled">Update</button>
            <button type="button" class="btn btn-primary" id="news-preview">Preview</button>
            <!-- <button type="button" class="btn btn-danger">Delete</button> -->
        </form>
    </div>
</div>
<div id="loading-panel" style="position: fixed;width: 300px;height: 60px;text-align: center;line-height: 60px;z-index: 10000;background-color: black;left: 50%;margin-left: -150px;top: 50%;margin-top: -30px;opacity: 0.75;color: white;display: none;">Article banner image uploading...</div>
<script type="text/javascript">
$(function(){
var _get = Api.Params()['id'];
var newsBannerUrl = [];
var oldNewsData = {
    title : false,
    author : false,
    content : false,
    category : false,
};
var bannerChanged = false;
Api.Get('getNewsDetail', Api.Params()['id'], function(object, error){
    if(object['message'] && object['status_code'] && object['message'] == 'OK' && object['status_code'] == 200 && object['data']['detail']){
        var news = object['data']['detail'][0];
        if(news){
            $('#news-status option[value="'+news['status']+'"]').attr('selected', 'selected');
            oldNewsData = {
                title : news['title'],
                author : news['author'],
                content : news['content'],
                category : news['category_id'],
            };
            $('#news-id').val(news['id']);
            $('#news-title').val(news['title']);
            $('#news-author').val(news['author']);
            $('#summernote').code(news['content']);
            $('#news-category-select').val(news['category_id']);
            try{
                var banner = JSON.parse(news['banner']);
                if(banner[0]){
                    $('#input-file-now-custom-1').data('default-file', banner[0]);
                    newsBannerUrl[0] = banner[0];
                }
                if(banner[1]){
                    $('#input-file-now-custom-2').data('default-file', banner[1]);
                    newsBannerUrl[1] = banner[1];
                }
                if(banner[2]){
                    $('#input-file-now-custom-3').data('default-file', banner[2]);
                    newsBannerUrl[2] = banner[2];
                }
            }catch(e){

            }
                
            $('.news-banner-img').dropify({error: {
                'minWidth': '[width=1600px & height=900px] please.',
                'maxWidth': '[width=1600px & height=900px] please.',
                'minHeight': '[width=1600px & height=900px] please.',
                'maxHeight': '[width=1600px & height=900px] please.',
            }}).on('dropify.afterClear', function(event, element){
                $('#save-news-btn').removeAttr('disabled');
                bannerChanged = true;
            }).on('dropify.error.minWidth', function(event, element){
                $.showError('[width=1600px & height=900px] please.', 400, function(){});
            }).on('dropify.error.maxWidth', function(event, element){
                $.showError('[width=1600px & height=900px] please.', 400, function(){});
            }).on('dropify.error.minHeight', function(event, element){
                $.showError('[width=1600px & height=900px] please.', 400, function(){});
            }).on('dropify.error.maxHeight', function(event, element){
                $.showError('[width=1600px & height=900px] please.', 400, function(){});
            });;
            Api.Get('getNewsCategoryList', {category_status:JSON.stringify([1])}, function(object, error){
                if(object['message'] && object['status_code'] && object['message'] == 'OK' && object['status_code'] == 200){
                    var categoryHtml = '<option value="0">Please select</option>', 
                        categoriesData = object['data']['data'];
                    for(var i=0; i<categoriesData.length; ++i){
                        categoryHtml += Api.render('<option value="{cid}">{cname}</option>', {
                            cid : categoriesData[i]['id'],
                            cname : categoriesData[i]['category_name'],
                        });
                    }
                    $('#news-category-select').html(categoryHtml);
                    $('#news-category-select option[value="'+news['category_id']+'"]').attr('selected', 'selected');
                }
            });
        }
    }else{
        $.showError('Something Error, Retry Please.', 300, function(obj){
            window.location.href = '/Article/index.html';
        });
    }
});
$('#news-title').keyup(function(){
    var hasC = hasChanged();
    if(hasC){
        $('#save-news-btn').removeAttr('disabled');
    }else{
        $('#save-news-btn').attr('disabled', 'disabled');
    }
});
$('.news-banner-img').change(function(){
    $('#save-news-btn').removeAttr('disabled');
    bannerChanged = true;
});
$('#news-author').keyup(function(){
    var hasC = hasChanged();
    if(hasC){
        $('#save-news-btn').removeAttr('disabled');
    }else{
        $('#save-news-btn').attr('disabled', 'disabled');
    }
});
$('#news-category-select').change(function(){
    var hasC = hasChanged();
    if(hasC){
        $('#save-news-btn').removeAttr('disabled');
    }else{
        $('#save-news-btn').attr('disabled', 'disabled');
    }
});
window.summernoteChanged = function(content){
    var hasC = hasChanged(content);
    if(hasC){
        $('#save-news-btn').removeAttr('disabled');
    }else{
        $('#save-news-btn').attr('disabled', 'disabled');
    }
}
function hasChanged(content=false){
    if(bannerChanged){
        return true;
    }
    if(oldNewsData['title'] && $('#news-title').val().trim() != oldNewsData['title']){
        return true;
    }
    if(oldNewsData['author'] && $('#news-author').val().trim() != oldNewsData['author']){
        return true;
    }
    if(oldNewsData['category'] && $('#news-category-select').val() != oldNewsData['category']){
        return true;
    }
    if(content && content != oldNewsData['content']){
        return true;
    }
    return false;
}
$('#news-preview').click(function(){
    var newsTitle = $('#news-title').val().trim();
    if(0 == newsTitle.length){
        $.showError('Article title can not be empty.', 300, function(){}, 2000);
        return false;
    }
    var newsAuthor = $('#news-author').val().trim();
    if(0 == newsAuthor.length){
        $.showError('Article author can not be empty.', 300, function(){}, 2000);
        return false;
    }
    var newsContent = $('#summernote').code();
    if(0 == newsContent.length){
        $.showError('Article content can not be empty.', 300, function(){}, 2000);
    }
    var newsCategoryId = parseInt($('#news-category-select').val());
    // var newsCategoryId = 1;
    if(newsCategoryId < 1){
        $.showError('Article category can not be empty.', 300, function(){}, 2000);
        return false;
    }
    var formdata = new FormData();  
    if($('.news-banner-img').length){
        $('.news-banner-img').each(function(i, obj){
            for(var j=0; j<obj.files.length; ++j){
                formdata.append('file['+i+'-'+j+']', obj.files[j]); 
            }
        });
    }
    if(formdata){
        $.ajax({
            data: formdata,  
            type: "POST",  
            url: API_HOSTNAMES['document']+'/public/uploadImages',  
            cache: false,  
            contentType: false,  
            processData: false,  
            success: function(rtn) {
                if(rtn['message'] && rtn['status_code'] && rtn['status_code'] == 200 && rtn['message'] == 'success'){
                    // newsBannerUrl.push(rtn['data'][k]);
                    try{
                        if(rtn['data']['0-0']){
                            newsBannerUrl[0] = rtn['data']['0-0'];
                        }
                        if(rtn['data']['1-0']){
                            newsBannerUrl[1] = rtn['data']['1-0'];
                        }
                        if(rtn['data']['2-0']){
                            newsBannerUrl[2] = rtn['data']['2-0'];
                        }
                    }catch(e){

                    }
                }
                var newsData = {title:newsTitle, author:newsAuthor, content:newsContent, banner:JSON.stringify(newsBannerUrl), category_id:newsCategoryId, status:3, handler:1};
                Api.Post('createNews', newsData,
                    function(object, error){
                        $('#loading-panel').hide();
                        if(object['message'] && object['status_code'] && object['message'] == 'OK' && object['status_code'] == 200){
                            window.open(Api.U('/preview/{aid}', {aid:object['data']['id']}, API_HOSTNAMES['pc']), 'preview');
                        }else{
                            $.showError('Something Error, Retry Please.', 300, function(){
                                window.location.reload();
                            });
                        }
                });
            }
        }); 
    }
    return false;
});
    $('#save-news-btn').click(function(){
        var newsStatus = $('#news-status').val();
        var newsTitle = $('#news-title').val().trim();
        if(0 == newsTitle.length){
            $.showError('Article title can not be empty.', 300, function(){}, 2000);
            return false;
        }
        var newsAuthor = $('#news-author').val().trim();
        if(0 == newsAuthor.length){
            $.showError('Article author can not be empty.', 300, function(){}, 2000);
            return false;
        }
        var newsContent = $('#summernote').code();
        if(0 == newsContent.length){
            $.showError('Article content can not be empty.', 300, function(){}, 2000);
            return false;
        }
        var newsCategoryId = parseInt($('#news-category-select').val());
        // var newsCategoryId = 1;
        if(newsCategoryId < 1){
            $.showError('Article category can not be empty.', 300, function(){}, 2000);
            return false;
        }
        var formdata = new FormData();  
        if($('.news-banner-img').length){
            $('.news-banner-img').each(function(i, obj){
                for(var j=0; j<obj.files.length; ++j){
                    formdata.append('file['+i+'-'+j+']', obj.files[j]); 
                }
            });
        }
        if(formdata){
            $('#loading-panel').show();
            $.ajax({
                data: formdata,  
                type: "POST",  
                url: API_HOSTNAMES['document']+'/public/uploadImages',  
                cache: false,  
                contentType: false,  
                processData: false,  
                success: function(rtn) {
                    $('#loading-panel').hide();
                    if(rtn['message'] && rtn['status_code'] && rtn['status_code'] == 200 && rtn['message'] == 'success'){
                        // newsBannerUrl.push(rtn['data'][k]);
                        try{
                            if(rtn['data']['0-0']){
                                newsBannerUrl[0] = rtn['data']['0-0'];
                            }
                            if(rtn['data']['1-0']){
                                newsBannerUrl[1] = rtn['data']['1-0'];
                            }
                            if(rtn['data']['2-0']){
                                newsBannerUrl[2] = rtn['data']['2-0'];
                            }
                        }catch(e){

                        }
                    }

                    var newsData = {id:$('#news-id').val(),title:newsTitle, author:newsAuthor, content:newsContent, banner:JSON.stringify(newsBannerUrl), category_id:newsCategoryId, status:newsStatus, handler:1};
                    $('#loading-panel').html('Saving Article Data...');
                    $('#loading-panel').show();
                    Api.Post('saveNews', newsData,
                        function(object, error){
                            $('#loading-panel').hide();
                            if(object['message'] && object['status_code'] && object['message'] == 'OK' && object['status_code'] == 200){
                                $.showSuccess('Save News Successfully.', 300, function(){
                                    window.location.href = '/Article/index.html';
                                });
                            }else{
                                $.showError('Something Error, Retry Please.', 300, function(){
                                    // window.location.reload();
                                });
                            }
                    });
                }  
            }); 
        }
        return false;
    });
});
</script>


    </div>
	
	<!-- Modal -->
	<div class="modal fade" id="confirmModal" aria-hidden="true" role="dialog" tabindex="-1">
	  <div class="modal-dialog modal-center">
		<div class="modal-content">
		  <div class="modal-header">
			<h4 class="modal-title"></h4>
		  </div>
		  <div class="modal-body">
			<p></p>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
			<button type="button" class="btn btn-primary"></button>
		  </div>
		</div>
	  </div>
	</div>
	<div class="modal fade" id="alertModal" aria-hidden="true" role="dialog" tabindex="-1">
	  <div class="modal-dialog modal-center">
		<div class="modal-content">
		  <div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				<span aria-hidden="true">×</span>
            </button>
			<h4 class="modal-title"></h4>
		  </div>
		  <div class="modal-body">
			<p></p>
		  </div>
		</div>
	  </div>
	</div>
	<!-- End Modal -->
  </div>
  <!-- End Page -->

  <!-- Footer -->
  <script type="text/javascript" src="../_resource/js/footer.js"></script>

    <script>
    (function(document, window, $) {
      'use strict';

      var Site = window.Site;
      $(document).ready(function() {
        Site.run();
          $('textarea[maxlength]').maxlength({
              threshold: 1000,
              placement: 'bottom-left-inside'
          });

          $.components.register("datepicker",{mode:"default",defaults:{autoclose:!0}});

        if (RUN_FUNCS.length > 0) {
          for(var i = 0; i < RUN_FUNCS.length; i++) {
            RUN_FUNCS[i].call();
          }
        }
      });
    })(document, window, jQuery);


  </script>
</body>
</html>